﻿using AiMoCore;
using AiMoWindows.GHAiMo;
using Rhino;
using System;
using System.Reflection;

namespace AiMoInGH.Connector
{
    class GHAiMoExecutor : IDisposable
    {
        public string CurrentDllPath { get; } = "";
        public GHCSharpScriptInstance CurrentInstance { get; }
        public ParamInfo[] Inputs { get; }
        public ParamInfo[] Outputs { get; }
        public GH_ParamSyntaxNodeInfo[] NewParamInfos { get; private set; } = Array.Empty<GH_ParamSyntaxNodeInfo>();
        //readonly GHScriptSource m_CurrentScripts;
        public GHAiMoExecutor(string currentDllPath, GHCSharpScriptInstance currentInstance, GHScriptSource currentScripts)
        {
            CurrentDllPath = currentDllPath;
            CurrentInstance = currentInstance;
            //m_CurrentScripts = currentScripts;

            Inputs = ParamAnalyzer.GetInputInfo(currentScripts.ParamInfos);
            Outputs = ParamAnalyzer.GetOutputInfo(currentScripts.ParamInfos);
        }
        public void Onload()
        {
            try
            {
                CurrentInstance.OnLoad();
            }
            catch (Exception ex)
            {
                RhinoApp.WriteLine("AiMo Grasshopper Script OnLoad Running Error\n" + ex);
            }
        }
        public void Dispose()
        {
            try
            {
                CurrentInstance.OnDelete();
            }
            catch (Exception ex)
            {
                RhinoApp.WriteLine("AiMo Grasshopper Script OnLoad Running Error\n" + ex);
            }
        }

        public static GHAiMoExecutor LoadFrom(string dllPath, GHScriptSource currentScripts, out string error)
        {
            try
            {
                Assembly assembly = Assembly.LoadFrom(dllPath);
                object objectValue = assembly.CreateInstance("Script_Instance");
                if (objectValue is GHCSharpScriptInstance instance)
                {
                    error = "";
                    return new GHAiMoExecutor(dllPath, instance, currentScripts);
                }
                error = "Dll Type is not supported";
                return null;
            }
            catch (Exception ex)
            {
                error = "Cannot load dll:" + ex;
                return null;
            }
        }
    }
}
